package com.hjy.core.transport.socket.server;

import com.hjy.common.entity.RpcRequest;
import com.hjy.common.entity.RpcResponse;
import com.hjy.core.handler.RequestHandler;
import com.hjy.core.provider.ServiceProvider;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * 向线程池中提交的任务
 */
@Data
@AllArgsConstructor
public class RequestHandlerThread implements Runnable {

    private Socket socket;
    private RequestHandler requestHandler;
    private ServiceProvider serviceProvider;

    @Override
    public void run() {
        try (ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream())) {
            // 获取 RpcRequest 对象
            RpcRequest rpcRequest = (RpcRequest) objectInputStream.readObject();
            // 获取服务对象
            Object service = serviceProvider.getService(rpcRequest.getInterfaceName());
            // 执行方法, 返回结果
            Object returnObject = requestHandler.handle(rpcRequest,service);
            objectOutputStream.writeObject(RpcResponse.success(returnObject));
            objectOutputStream.flush();
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("调用或发送时有错误发生：" + e.toString());
        }
    }
}
